package cn.chason678.springbootwebdemo.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * Created by HuYong on 2020/4/15.
 */
@Configuration //注解到spring容器中
@MapperScan(basePackages = "cn.chason678.springbootwebdemo.cn.repository",sqlSessionFactoryRef = "dataCnSqlSessionFactory")
public class DataSourceCn {

    static final String MAPPER_LOCATION = "classpath:cn_mapper/*.xml";

    @Value("${spring.datasource.datacn.url}")
    private String url;

    @Value("${spring.datasource.datacn.username}")
    private String user;

    @Value("${spring.datasource.datacn.password}")
    private String password;

    @Value("${spring.datasource.datacn.driver-class-name}")
    private String driverClass;

    /**
     * 返回data1数据库的数据源
     * @return
     */
    @Bean(name="dataCnSource")
    @Primary //主数据源
    public DataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }

    /**
     * 返回data1数据库的会话工厂
     * @param ds
     * @return
     * @throws Exception
     */
    @Bean(name = "dataCnSqlSessionFactory")
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dataCnSource") DataSource ds) throws Exception{
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(ds);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(DataSourceCn.MAPPER_LOCATION));
        return bean.getObject();
    }

    /**
     * 返回data1数据库的会话模板
     * @param sessionFactory
     * @return
     * @throws Exception
     */
    @Bean(name = "dataCnSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("dataCnSqlSessionFactory") SqlSessionFactory sessionFactory) throws  Exception{
        return  new SqlSessionTemplate(sessionFactory);
    }

    /**
     * 返回data1数据库的事务
     * @param ds
     * @return
     */
    @Bean(name = "dataCnTransactionManager")
    @Primary
    public DataSourceTransactionManager transactionManager(@Qualifier("dataCnSource") DataSource ds){
        return new DataSourceTransactionManager(ds);
    }
}
